/**
 * Created by Dalyn on 2017/3/21.
 */
import React from "react";
import "./css/settlementProcess.css";
import Confirm from "../../common/Confirm"
import {hashHistory} from 'react-router';
import Relay from "react-relay";
import { message } from 'antd';
import FileUpData from './components/FileUpDataPro'  //上传附件
import ApplyEnBalanceMutation from './mutation/ApplyEnBalanceMutation'
import GetQiNiuToken from "./mutation/FindSewRawListMutation"  //上传图片获取token
import {Button} from 'fly';
import Config from "../../util/Config"
/*导出组件*/
export default class SettlementProcess extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            displayflag: true,
            isRelay:true,
            status:"",
            orderId:"",
            invoiceMoney:"",
            hint:"",
            token: '',

            invoiceNum: '',//发票张数
            expressName: '',//快递公司
            expressSheet: '',//快递单号
            invoiceFileJson: [],//发票附件
            invoiceNumHint: false,
            expressNameHint: false,
            expressSheetHint: false,
            invoiceFileJsonHint: false,
            highLight1: false,
            highLight2: false,
            highLight3: false,
        };
        this.style = {
            confirm: {
                width: '100px',
                height: '28px',
                backgroundColor: "#36b3b3",
                fontSize: "14px",
                color: "#fff",
                // marginTop: "16px",
                marginLeft: "20px",
                fontFamily: "Microsoft YaHei"
            },
        }
        this.addFileItem = this.addFileItem.bind(this); //上传文件 更新内部状态list
    }



    componentWillMount(){
        if(this.props.location.state.status == "1" || this.props.location.state.status == "5"){
            this.setState({
                displayflag:false,
            });
        }
        this.setState({
            status:this.props.location.state.status,
            orderId:this.props.location.state.orderId,
            invoiceMoney:this.props.location.state.invoiceMoney,
        });
        //获取上传图片所需的token
        Relay.Store.commitUpdate(
            new GetQiNiuToken({}), {
                onSuccess: (res) => {
                    let errorCode = res.getQiNiuToken.getQiNiuToken.errorCode;
                    if(errorCode==0){
                        let qiniutoken = res.getQiNiuToken.getQiNiuToken.qiniutoken;
                        this.setState({
                            token:qiniutoken
                        })
                    }else if(errorCode==500){
                        message.error("服务器错误，请联系管理员")
                    }
                },
                onFailure:()=>{
                    message.error("网络请求失败 ")
                }
            }
        );

    }
    relayApply() {
        Relay.Store.commitUpdate(
            new ApplyEnBalanceMutation({
                orderId: this.state.orderId,
                invoiceNum: this.state.invoiceNum,  //发票张数
                expressName: this.state.expressName,  //快递公司
                expressSheet: this.state.expressSheet,  //快递单号
                invoiceFileJson: JSON.stringify(this.state.invoiceFileJson),  //发票附件
                status: 2
            }),
            {
                onFailure: () => {
                    message.error("请求失败")
                },
                onSuccess: (response) => {
                    let data = response.applyEnBalance.data;
                    if (data.errorCode === "0") {
                        message.info("申请成功")
                        /*请求成功*/
                        hashHistory.push("/settlementrecord")
                    } else {
                        message.error(data.value)
                        this.setState({
                            hint: data.value
                        });
                    }
                }

            }
        );
    }
    /*点击确认*/
    handleConfirm() {
      if (this.state.invoiceNum == '' || this.state.invoiceNum == 0) {
        this.setState({
          invoiceNumHint: true,
        })
      }
      if (this.state.expressName == '') {
        this.setState({
          expressNameHint: true,
        })
      }
      if (this.state.expressSheet == '') {
        this.setState({
          expressSheetHint: true,
        })
      }
      if (this.state.invoiceFileJson == '') {
        this.setState({
          invoiceFileJsonHint: true,
        })
      }
      if(this.state.invoiceFileJson[0] && this.state.invoiceFileJson[0].status !== "done"){
        message.info("请等待上传文件完成");
        return ;
      }
      if (this.state.invoiceNum != '' && this.state.invoiceNum != 0 &&
          this.state.expressName != '' &&
          this.state.expressSheet != '' &&
          this.state.invoiceFileJson != '') {
            this.relayApply();
          }

    }
    /*点击返回*/
    handleCancel() {
        hashHistory.push("/settlementrecord")
    }
    /*营业执照*/
    downLoad_license(){
        window.open(Config.qiuniu+"569659948.jpg")
    }
    /*纳税人资质下载*/
    downLoad(){
        window.open(Config.qiuniu+"一般纳税人资质说明.docx")
    }
    // 上传文件配置
    fileUploadPlugin = {
        action: 'http://up-z2.qiniu.com',
        beforeUpload:this.fileBeforeload,
        maxlength:5
    };

    //附件上传之前验证...
    fileBeforeload(file){
        const MaxSize = 50;  //最大限度 10M;

        if( file.size / 1024 / 1024 > MaxSize ){
            message.error("文件大小超过限制");
            return false;
        }

        if(file.type == "image/jpeg" ||
          file.type == "image/jpg" ||
          file.type == "image/png" ||
          file.type == "image/gif" ||
          file.type == "image/bmp" ||
          file.name.slice(file.name.lastIndexOf(".")) == ".rar" ||
          file.name.slice(file.name.lastIndexOf(".")) == ".zip"
        ){}else{
           message.info('文件格式不正确')
           return false;

        }
    }


    // 新增文件函数，（push 当前组件）
    addFileItem(fileList){
        this.state.invoiceFileJson = fileList;
        this.setState({
            invoiceFileJson:this.state.invoiceFileJson,
            invoiceFileJsonHint: false
        })
    }

    handleClickSelf(){
        message.warning("附件最多允许上传5个")
    }

    changeInput(type, e) {
      const reg = /^\d{0,3}$/
      const regs = /^[0-9a-zA-Z]*$/g;
      if (type == 'invoiceNum') {
        if (!reg.test(e.target.value) && e.target.value != '') {
          return;
        }
        if (e.target.value.length>3) {
          e.target.value = e.target.value.toString().substring(0,3);
          return;
        }
      } else {
        if (type == 'expressSheet' && !regs.test(e.target.value) && e.target.value != '') {
          return;
        }
        if (e.target.value.indexOf(' ') > -1) {
          return
        }
         if (e.target.value.length>20) {
          e.target.value = e.target.value.toString().substring(0,20);
          return;
        }
      }

      if (type == 'invoiceNum') {
        this.setState({
          invoiceNumHint: false,
          invoiceNum: e.target.value
        })
      } else if (type == 'expressName') {
        this.setState({
          expressNameHint: false,
          expressName: e.target.value
        })
      } else if (type == 'expressSheet') {
        this.setState({
          expressSheetHint: false,
          expressSheet: e.target.value
        })
      }
    }

    inputFocus(type) {
        if (type == 'invoiceNum') {
            this.setState({
                highLight1: true
            })
        } else if (type == 'expressName') {
            this.setState({
                highLight2: true
            })
        } else if (type == 'expressSheet') {
            this.setState({
                highLight3: true
            })
        }
    }
    inputBlur(){
        this.setState({
            highLight1: false,
            highLight2: false,
            highLight3: false
        })

    }

    render(){
      const { invoiceFileJson,token, invoiceNum, expressName, expressSheet, invoiceNumHint,expressNameHint, expressSheetHint,invoiceFileJsonHint } = this.state
        return (
            <div className="settle_pro_bg">
                <div className="settle_pro_box">
                    <div className="settle_pro_imgBox">
                        <span>结算流程：</span>
                        <i className="settle_pro_timg"></i>
                        <p className="settle_pro_step">
                            <span>1</span>
                            <span>2</span>
                            <span>3</span>
                            <span></span>
                        </p>
                        <p className="settle_pro_tp">
                            <span className="settle_pro_first">申请结算方开出发票</span>
                            <span className="settle_pro_second">寄送发票到指定地址</span>
                            <span className="settle_pro_three">验收发票</span>
                            <span className="settle_pro_four">打款到申请结算方的企业账户</span>
                        </p>
                    </div>
                    <div className="settle_pro_context">
                        <div className="settle_pro_info">
                            <p className="settle_pro_bill">开票信息<span className="settle_pro_billspan settle_pro_red">*请仔细填写以下信息，开票时务必要正确填写，否则会影响结算</span></p>
                            <p className="settle_pro_money">
                                <span className="settle_pro_name">开票金额：</span>
                                <span className="settle_pro_moneyspan">{this.state.invoiceMoney}</span>元</p>
                            <p className="settle_pro_p">
                                <span className="settle_pro_name">名称：</span>
                                <span className="settle_pro_span">青岛尚德工贸有限公司</span>
                            </p>
                            <p className="settle_pro_p">
                                <span className="settle_pro_name">纳税人识别码：</span>
                                <span className="settle_pro_span">913702027472472128</span>
                            </p>
                            <p className="settle_pro_p">
                                <span className="settle_pro_name">地址/电话：</span>
                                <span className="settle_pro_span">青岛市南区东海西路5号甲1005室  0532-85880016</span>
                            </p>
                            <p className="settle_pro_p">
                                <span className="settle_pro_name">开户行及账号：</span>
                                <span className="settle_pro_span">华夏银行香港中路支行 4671310001810200053547</span></p>
                        </div>
                        <div className="settle_pro_infodown">
                            <p className="settle_pro_bill">邮寄信息</p>
                            <p className="settle_pro_p1">
                                <span className="settle_pro_name">收票人姓名：</span>
                                <span className="settle_pro_span">李梅</span>
                            </p>
                            <p className="settle_pro_p">
                                <span className="settle_pro_name">收票人电话：</span>
                                <span className="settle_pro_span">0532-85876111</span>
                            </p>
                            <p className="settle_pro_p">
                                <span className="settle_pro_name">收票人地址：</span>
                                <span className="settle_pro_span">青岛市市南区东海西路5号甲华银大厦1006室</span>
                            </p>
                            <p className="settle_pro_p">
                                <span className="settle_pro_lan0" onClick={this.downLoad_license.bind(this)}>营业执照</span>
                                {/*<span className="settle_pro_lan" onClick={this.downLoad.bind(this)}>一般纳税人资质下载</span>*/}
                            </p>
                        </div>
                        <p className="settle_pro_ps"><a href="">注：</a>订单结算需将代付款协议甲乙双方盖章后，同发票一起寄送到平台，否则不予结算代付款协议可在合同管理中进行下载
                        </p>
                        <div className='settle_pro_edit settle_pro_info'>

                          <ul className='settle_pro_ul'>
                              <li>
                                  <span className="settle_pro_title">发票张数</span>
                                  <input
                                      onFocus={this.inputFocus.bind(this, 'invoiceNum')}
                                      onBlur={this.inputBlur.bind(this)}
                                      value={invoiceNum}
                                      type="text"
                                      style={this.state.highLight1 ? {'border':'1px solid #36b3b3'}:{}}
                                      onChange={this.changeInput.bind(this,'invoiceNum')}
                                  />
                                  <span className={invoiceNumHint ? 'settle_pro_hint' : 'settle_pro_hint_disn'}>请输入发票张数</span>
                            </li>
                              <li>
                                  <span className="settle_pro_title">快递公司</span>
                                  <input
                                      onFocus={this.inputFocus.bind(this,'expressName')}
                                      onBlur={this.inputBlur.bind(this)}
                                      value={expressName}
                                      type="text"
                                      style={this.state.highLight2 ? {'border':'1px solid #36b3b3'}:{}}
                                      onChange={this.changeInput.bind(this,'expressName')}
                                  />
                                  <span className={expressNameHint ? 'settle_pro_hint' : 'settle_pro_hint_disn'}>请输入快递公司</span>
                              </li>
                              <li>
                                  <span className="settle_pro_title">快递单号</span>
                                  <input
                                      onFocus={this.inputFocus.bind(this,'expressSheet')}
                                      onBlur={this.inputBlur.bind(this)}
                                      value={expressSheet}
                                      type="text"
                                      style={this.state.highLight3 ? {'border':'1px solid #36b3b3'}:{}}
                                      onChange={this.changeInput.bind(this,'expressSheet')}
                                  />
                                  <span className={expressSheetHint ? 'settle_pro_hint' : 'settle_pro_hint_disn'}>请输入快递单号</span>
                              </li>
                              <li>
                                  <span className="settle_pro_title">发票附件</span>
                                    {/*附件 列表*/}
                                    <FileUpData
                                        className="packagSteps_updataFile process_demandlook process_delete"
                                        filePlugin={this.fileUploadPlugin}
                                        fileList={invoiceFileJson}
                                        callBack={this.addFileItem}
                                        token={token}
                                        isShowTrigger={invoiceFileJson.length < this.fileUploadPlugin.maxlength}
                                        handleClickSelf={this.handleClickSelf}
                                    />
                                  <span className="settle_ord_hint">（附件最大50M，支持格式：RAR、ZIP、BMP、JPEG、JPG、GIF、PNG）</span>
                                  <span className={invoiceFileJsonHint ? 'settle_pro_hint' : 'settle_pro_hint_disn'}>请上传不超过50M的RAR、ZIP、BMP、JPEG、JPG、GIF、PNG格式的文件</span>

                            </li>
                          </ul>
                        </div>
                        {this.state.displayflag
                            ?
                            (
                                <div className="settle_pro_buttonBox1 clear">
                                    <Confirm style={this.style.confirm} tcontext={'返回'} touch={this.handleCancel.bind(this)}/>
                                </div>
                            )
                            :
                            (
                                <div className="settle_pro_buttonBox2 clear">
                                    <Button onClick={this.handleConfirm.bind(this)}>申请</Button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    <Button onClick={this.handleCancel.bind(this)}>返回</Button>
                                    {/*<Confirm style={this.style.confirm} tcontext={'申请'} touch={this.handleConfirm.bind(this)}/>*/}
                                    {/*<Confirm style={this.style.confirm} tcontext={'返回'} touch={this.handleCancel.bind(this)}/>*/}
                                </div>
                            )
                        }
                    </div>
                </div>
            </div>
        )
    }
}
